import { useState, useCallback, useEffect } from 'react';
import { useLocalStorage } from './useLocalStorage';
import { SeriesItem, ChartType } from '../types';
import { message } from 'antd';

/**
 * 默认预设样式 - 按图表类型分类
 */
const DEFAULT_PRESETS: Record<string, Record<string, SeriesItem>> = {
  // 折线图预设
  'line': {
    '简约折线': {
      type: 'line',
      name: '数据系列',
      color: '#5470c6',
      smooth: false,
      symbol: 'emptyCircle',
      symbolSize: 4,
      lineStyle: {
        width: 2,
        type: 'solid'
      },
      emphasis: {
        focus: 'series'
      }
    },
    '平滑曲线': {
      type: 'line',
      name: '数据系列',
      color: '#5470c6',
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      lineStyle: {
        width: 3,
        type: 'solid'
      },
      emphasis: {
        focus: 'series'
      }
    },
    '面积图': {
      type: 'line',
      name: '数据系列',
      color: '#91cc75',
      smooth: true,
      symbol: 'none',
      areaStyle: {
        opacity: 0.3
      },
      emphasis: {
        focus: 'series'
      }
    },
    '科技风格': {
      type: 'line',
      name: '数据系列',
      color: '#5470c6',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 3,
        type: 'solid',
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowBlur: 10,
        shadowOffsetY: 5
      },
      emphasis: {
        itemStyle: {
          shadowColor: 'rgba(0, 0, 0, 0.5)',
          shadowBlur: 15
        }
      },
      itemStyle: {
        borderWidth: 2,
        borderColor: '#fff',
        shadowColor: 'rgba(0, 0, 0, 0.2)',
        shadowBlur: 5
      }
    }
  },
  
  // 柱状图预设
  'bar': {
    '简约柱图': {
      type: 'bar',
      name: '数据系列',
      color: '#5470c6',
      barWidth: 20,
      emphasis: {
        focus: 'series'
      }
    },
    '渐变柱图': {
      type: 'bar',
      name: '数据系列',
      color: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [
          { offset: 0, color: '#83bff6' },
          { offset: 1, color: '#188df0' }
        ]
      },
      barWidth: 25,
      emphasis: {
        focus: 'series'
      }
    },
    '圆角柱图': {
      type: 'bar',
      name: '数据系列',
      color: '#91cc75',
      barWidth: 25,
      itemStyle: {
        borderRadius: 5
      },
      emphasis: {
        focus: 'series'
      }
    },
    '背景柱图': {
      type: 'bar',
      name: '数据系列',
      color: '#5470c6',
      barWidth: 25,
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        borderRadius: 5
      },
      emphasis: {
        focus: 'series'
      }
    }
  },
  
  // 饼图预设
  'pie': {
    '简约饼图': {
      type: 'pie',
      name: '数据系列',
      radius: '70%',
      emphasis: {
        focus: 'self',
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    },
    '环形图': {
      type: 'pie',
      name: '数据系列',
      radius: ['50%', '70%'],
      avoidLabelOverlap: true,
      emphasis: {
        focus: 'self',
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        show: false
      }
    },
    '南丁格尔图': {
      type: 'pie',
      name: '数据系列',
      radius: '70%',
      roseType: 'radius',
      emphasis: {
        focus: 'self'
      }
    },
    '标签饼图': {
      type: 'pie',
      name: '数据系列',
      radius: '60%',
      label: {
        show: true,
        formatter: '{b}: {d}%',
        fontSize: 14
      },
      emphasis: {
        focus: 'self',
        label: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      }
    }
  },
  
  // 散点图预设
  'scatter': {
    '简约散点': {
      type: 'scatter',
      name: '数据系列',
      color: '#5470c6',
      symbolSize: 10,
      emphasis: {
        focus: 'self'
      }
    },
    '气泡图': {
      type: 'scatter',
      name: '数据系列',
      color: '#91cc75',
      symbolSize: 20,
      itemStyle: {
        opacity: 0.7,
        borderColor: '#fff',
        borderWidth: 1,
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowBlur: 5
      },
      emphasis: {
        focus: 'self',
        itemStyle: {
          opacity: 1,
          borderWidth: 2,
          shadowBlur: 10
        }
      }
    },
    '阴影散点': {
      type: 'scatter',
      name: '数据系列',
      color: '#5470c6',
      symbolSize: 15,
      itemStyle: {
        shadowBlur: 10,
        shadowColor: 'rgba(0, 0, 0, 0.3)',
        shadowOffsetY: 5
      },
      emphasis: {
        focus: 'self',
        itemStyle: {
          shadowBlur: 20
        }
      }
    }
  }
};

export interface SeriesPreset {
  name: string;
  config: SeriesItem;
  isDefault: boolean;
}

/**
 * 系列预设钩子 - 管理系列样式预设
 */
export function useSeriesPresets(chartType: ChartType) {
  // 从本地存储加载用户自定义预设
  const [customPresets, setCustomPresets] = useLocalStorage<Record<string, Record<string, SeriesItem>>>(
    'chart-editor-series-presets',
    {}
  );

  // 合并默认预设和自定义预设
  const [allPresets, setAllPresets] = useState<SeriesPreset[]>([]);

  // 在默认预设和自定义预设变化时更新所有预设
  useEffect(() => {
    const chartTypeKey = chartType.toLowerCase();
    
    // 获取当前图表类型的默认预设
    const defaultTypedPresets = DEFAULT_PRESETS[chartTypeKey] || {};
    
    // 获取当前图表类型的自定义预设
    const customTypedPresets = customPresets[chartTypeKey] || {};
    
    const presetArray: SeriesPreset[] = [
      ...Object.entries(defaultTypedPresets).map(([name, config]) => ({
        name,
        config,
        isDefault: true
      })),
      ...Object.entries(customTypedPresets).map(([name, config]) => ({
        name,
        config,
        isDefault: false
      }))
    ];

    setAllPresets(presetArray);
  }, [customPresets, chartType]);

  // 保存当前配置为新预设
  const saveAsPreset = useCallback((name: string, config: SeriesItem) => {
    if (!name.trim()) {
      message.error('预设名称不能为空');
      return false;
    }

    const chartTypeKey = config.type.toLowerCase();
    
    // 检查是否与默认预设重名
    if (DEFAULT_PRESETS[chartTypeKey] && Object.keys(DEFAULT_PRESETS[chartTypeKey]).includes(name)) {
      message.error('不能覆盖默认预设');
      return false;
    }

    setCustomPresets(prev => {
      // 确保该图表类型的预设对象存在
      const chartTypePresets = prev[chartTypeKey] || {};
      
      return {
        ...prev,
        [chartTypeKey]: {
          ...chartTypePresets,
          [name]: JSON.parse(JSON.stringify(config)) // 深拷贝确保不受后续修改影响
        }
      };
    });

    message.success(`预设 "${name}" 已保存`);
    return true;
  }, [setCustomPresets]);

  // 删除自定义预设
  const deletePreset = useCallback((name: string) => {
    const chartTypeKey = chartType.toLowerCase();
    
    // 检查是否为默认预设
    if (DEFAULT_PRESETS[chartTypeKey] && Object.keys(DEFAULT_PRESETS[chartTypeKey]).includes(name)) {
      message.error('不能删除默认预设');
      return false;
    }

    setCustomPresets(prev => {
      const newPresets = { ...prev };
      
      if (newPresets[chartTypeKey]) {
        const chartTypePresets = { ...newPresets[chartTypeKey] };
        delete chartTypePresets[name];
        newPresets[chartTypeKey] = chartTypePresets;
      }
      
      return newPresets;
    });

    message.success(`预设 "${name}" 已删除`);
    return true;
  }, [chartType, setCustomPresets]);

  return {
    allPresets,
    customPresets,
    saveAsPreset,
    deletePreset
  };
}